package com.baboba.rummy.game;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import com.baboba.rummy.card.CardFactory;
import com.baboba.rummy.card.UserCard;
import com.baboba.rummy.card.arena.CardArena;
import com.baboba.rummy.player.Player;

public class GameRound implements PlayerStateChangedCallback{
	private Date startTime;
	private CardArena cardArena;
	private LinkedList<UserCard> cards;
	private Player[] players;
	private int currentPlayer = 0;
	
	public GameRound(){
		startTime = new Date();
		players = GameManager.getInstance().getPlayers();
		cards = CardFactory.generateRandomShownCardsAsList();
		cardArena = new CardArena();
	}
	
	public void begin(){
		LinkedList<UserCard>[] cardList = new LinkedList[players.length];
		
		for (int i=0;i<players.length;i++){
			cardList[i] = new LinkedList<UserCard>();
			players[i].setStateChangedCallback(this);
		}
		
		for (int i=0;i<14;i++){
			for (int l=0;l<players.length;l++){
				cardList[l].add(cards.poll());
			}
		}
		
		for (int i=0;i<players.length;i++){
			players[i].initFirstHandCards(cardList[i]);
		}
		
		startGameRound();
	}
	
	private void startGameRound() {
		getNextActivePlayer().nextStep();
	}

	private Player getNextActivePlayer(){
		if (currentPlayer>=players.length)
			currentPlayer = 0;
			
		return players[currentPlayer++];
	}

	@Override
	public void onFinishedStep(List<UserCard> cards) {
		getNextActivePlayer().nextStep();
	}

	@Override
	public void onFinisheIceBreak(List<LinkedList<UserCard>> cardList) {
		
	}
}
